import React from 'react';
import Api from 'Utils/api';
import { Form, message, Checkbox, Input, Button, AutoComplete } from 'antd';
import QRCode from 'qrcode.react';
import * as routerActions from 'react-router-redux';
import { connect } from 'react-redux';
import { chaeckMobilePhone, generateUUID } from 'Utils/index';
import { debounce } from 'throttle-debounce';
import { BROWSER_MODE } from 'Constants/webConstants';
import { CAPTCHA_SECONDS, QRCODE_HOST } from '../../../../constants/config';
import FlagTitle from '../../FlagTitle';
import './appointment.scss';


const FormItem = Form.Item;
const { TextArea } = Input;
let canSendCaptcha = true;
const CaptchaSeconds = CAPTCHA_SECONDS;
class MakeAppointment extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      initialValue: {},
      remainingSecond: CaptchaSeconds,
      loading: false,
      anonymous: false,
      qrCode: generateUUID(),
      business: [],
      selectBusinessName: '',
      selectBusinessType: '',
      dataList: [],
      businessId: ''
    };
    this.handSubmit = ::this.handSubmit;
    this.handClick = ::this.handClick;
    this.sendCaptcha = ::this.sendCaptcha;
    this.countDownSeconds = ::this.countDownSeconds;
    this.changeAnonymous = ::this.changeAnonymous;
    this.initBusiness = debounce(1000, ::this.initBusiness);
  }
  componentWillUnmount() {
    clearInterval(this.timer);
  }
  handClick() {
    this.props.dispatch(routerActions.goBack());
  }
  handSubmit() {
    const { selectBusinessName, dataList } = this.state;
    const formValue = this.props.form.getFieldsValue();
    const selectBusiObj = dataList.filter(item => item.name === formValue.company_name);
    if (!selectBusinessName || selectBusiObj.length === 0) {
      this.props.form.setFields({ company_name: { value: formValue.company_name, errors: [new Error('请在下拉框中选择预约的商家')] } });
      return;
    }
    this.props.form.validateFieldsAndScroll((err) => {
      if (!err) {
        // 检查手机号格式
        if (!chaeckMobilePhone(formValue.phone)) {
          message.info('联系电话格式错误', 3);
          return;
        }
        this.setState({ loading: true });
        const data = { ...formValue };
        data.is_anonymity = this.state.anonymous;
        data.uuid = this.state.qrCode;
        data.type = this.state.selectBusinessType;
        const sumApi = new Api({
          method: 'POST',
          path: '/randoms/user',
          data,
          success: () => {
            this.setState({ loading: false });
            this.handClick();
          },
          error: (msg) => {
            message.error(msg);
            this.setState({ loading: false });
          }
        });
        sumApi.run();
      }
    });
  }
  // 发送验证码
  sendCaptcha() {
    const phone = this.props.form.getFieldsValue().phone;
    if (!canSendCaptcha) {
      return;
    }

    if (!phone) {
      message.warning('请先输入手机号', 3);
      return;
    }
    // 检查手机号格式
    if (!chaeckMobilePhone(phone)) {
      message.info('联系电话格式错误', 3);
      return;
    }
    canSendCaptcha = false;
    setTimeout(() => {
      this.setState({
        remainingSecond: CaptchaSeconds,
      }, () => {
        this.countDownSeconds();
      });
    }, 0);

    const api = new Api({
      method: 'POST',
      path: '/phone/verify_code',
      data: {
        phone,
        response: 'tmind'
      },
      error: () => {
        this.setState({
          remainingSecond: 0,
        }, () => {
          canSendCaptcha = true;
          clearInterval(this.timer);
          this.timer = undefined;
        });
      },
    });
    api.run();
  }
  /**
   * 验证码倒计时
   */
  changeAnonymous(e) {
    this.setState({
      anonymous: e.target.checked,
    });
  }
  countDownSeconds() {
    const remainingSecond = this.state.remainingSecond - 1;
    if (remainingSecond < 0) {
      canSendCaptcha = true;
      clearInterval(this.timer);
      this.timer = undefined;
    } else {
      if (!this.timer) {
        this.timer = setInterval(this.countDownSeconds, 1000);
      }
      this.setState(preState => (Object.assign({}, preState, {
        remainingSecond,
      })));
    }
  }
  randomPeople() {
    const api = new Api({
      method: 'GET',
      query: {
        evade_executor: this.props.form.getFieldsValue().evade_executor
      },
      path: `/justices/random/${this.state.businessId}`,
      success: (res) => {
        if (res.length === 2) {
          this.props.form.setFieldsValue({ law_executor1: res[0].name || '' });
          this.props.form.setFieldsValue({ law_executor2: res[1].name || '' });
        }
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  // 选择商家
  handleSelect(value) {
    const { dataList } = this.state;
    const busiItem = dataList.filter((item) => {
      return item.name === value;
    });
    this.setState({
      selectBusinessName: busiItem.length > 0 ? busiItem[0].name : '',
      selectBusinessType: busiItem.length > 0 ? busiItem[0].type : '',
      businessId: busiItem.length > 0 ? busiItem[0].id : '',
    });
  }
  handleBusinessChange(value) {
    this.setState({
      inputValue: value.trim(),
    }, () => {
      if (this.state.inputValue) {
        this.initBusiness();
      }
    });
  }
  initBusiness() {
    const api = new Api({
      method: 'GET',
      path: '/enterprises',
      query: {
        name_like: this.state.inputValue,
        offset: 0,
        limit: 30
      },
      success: (res) => {
        const datas = res.data_list && res.data_list.length > 0 ? res.data_list : [];
        const business = datas.length > 0 ? res.data_list.map(item => item.name) : [];
        this.setState({
      //    selectBusinessName: datas.length > 0 ? datas[0].name : '',
      //    selectBusinessType: datas.length > 0 ? datas[0].type : '',
       //   businessId: datas.length > 0 ? datas[0].id : '',
          business: [...business],
          dataList: datas
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  randomBusiness() {
    const api = new Api({
      method: 'GET',
      path: '/enterprises/random',
      success: (res) => {
        const data = [];
        data.push(res);
        this.setState({
          selectBusinessName: res.name || '',
          selectBusinessType: res.type || '',
          businessId: res.id || '',
          dataList: [...data]
        });
        this.props.form.setFieldsValue({ company_name: res.name || '' });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  render() {
    const { form, mode } = this.props;
    const { getFieldDecorator } = form;
    const { remainingSecond, business, businessId } = this.state;
    const isVertical = BROWSER_MODE.isVertical(mode);
    return (
      <div className={`${isVertical ? 'v-' : ''}make-appointment-container`} >
        <div className="main-make-appointment" >
          <div className="header-appointment">
            <FlagTitle text="我要预约" />
          </div>
          <div className="form-content-wrap">
            <Form layout={'horizontal'} className="appointment-form" id="form">
              <FormItem label="商家名称" >
                {getFieldDecorator('company_name', {
                  rules: [
                    { required: true, message: '请选择商家名称' }
                  ]
                })(
                  <AutoComplete
                    dataSource={business}
                    placeholder="请选择商家名称"
                    defaultActiveFirstOption={false}
                    onSelect={this.handleSelect.bind(this)}
                    onChange={this.handleBusinessChange.bind(this)}
                    getPopupContainer={() => document.getElementById('form')}
                  />
                )}
                <Button className="btn-left" onClick={this.randomBusiness.bind(this)} >随机商家</Button >
              </FormItem >
              <FormItem label="申请回避人员" >
                {getFieldDecorator('evade_executor', {
                })(
                  <Input placeholder="请输入申请回避人员姓名" />
                )}
              </FormItem >
              <div className="law-officer">
                <FormItem label="执法人员">
                  {getFieldDecorator('law_executor1', {
                    rules: [
                      { required: true, message: '请选择执法人员' }
                    ]
                  })(
                    <Input placeholder="请选择执法人员" className="law-officer-input" disabled />
                  )}
                </FormItem >
                <FormItem >
                  {getFieldDecorator('law_executor2', {
                    rules: [
                      { required: true, message: '请选择执法人员' }
                    ]
                  })(
                    <Input placeholder="请选择执法人员" className="law-officer-input law-officer-second" disabled />
                  )}
                </FormItem >
                <Button className="random-person" disabled={!businessId} onClick={this.randomPeople.bind(this)} >随机人员</Button >
              </div>
              <FormItem label="申请人姓名" >
                {getFieldDecorator('name', {
                  rules: [
                    { required: true, message: '请输入您的姓名' }
                  ]
                })(
                  <Input placeholder="请输入举报人姓名" style={{ verticalAlign: 'top' }} />
                )}
                <div className="reporter-anonymous">
                  <Checkbox checked={this.state.anonymous} onChange={this.changeAnonymous}><span className="anonymous-text">匿名</span></Checkbox>
                </div>
              </FormItem >
              <FormItem label="身份证号" >
                {getFieldDecorator('id_no', {
                  rules: [
                    { required: true, message: '请输入您的身份证号' }
                  ]
                })(
                  <Input placeholder="请输入身份证号" />
                )}
              </FormItem >
              <FormItem label="联系电话" >
                {getFieldDecorator('phone', {
                  rules: [
                    { required: true, message: '请输入联系电话' }
                  ]
                })(
                  <Input placeholder="请输入联系电话" />
                )}
                <Button className="code" onClick={this.sendCaptcha} >
                  {remainingSecond === 60 || remainingSecond === 0
                    ? '获取验证码'
                    : <span>剩余{remainingSecond}s</span>
                  }
                </Button >
              </FormItem >
              <FormItem label="验证码" >
                {getFieldDecorator('code', {
                  rules: [
                    { required: true, message: '请输入验证码' }
                  ]
                })(
                  <Input placeholder="请输入验证码" />
                )}
              </FormItem >
              <FormItem label="内容" >
                {getFieldDecorator('content', {
                  rules: [
                    { required: true, message: '请输入内容' }
                  ]
                })(
                  <TextArea placeholder="请输入内容" rows={4} className="textarea" />
                )}
              </FormItem >
              <FormItem label="二维码" >
                <div style={{ width: 50, height: 50 }} >
                  <QRCode
                    level="Q"
                    value={`${QRCODE_HOST}?uuid=${this.state.qrCode}`}
                  />
                </div >
              </FormItem >
              <p className="text-content" >请用微信扫描二维码上传附件</p >
              <Button
                className="submit"
                onClick={this.handSubmit.bind(this)}
                loading={this.state.loading}
              >提交</Button >
              <div className="policeman">
                <div className="private" >预约人可放心填写，为保护投诉人隐私，个人信息不会被公开</div >
                <img src="images/pic_policeman.png" alt="" className="police-pic" />
              </div >
            </Form >
          </div>
        </div >
      </div >
    );
  }
}


function mapStateToProps(state) {
  return {
    ...state.route,
    ...state.webReducer
  };
}

export default Form.create()(connect(mapStateToProps)(MakeAppointment));
